package org.codefinger.dao.util.magic;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.codefinger.dao.util.Lang;

public class MagicClassLoader extends ClassLoader {

	private MagicClassLoader(ClassLoader classLoader) {
		super(classLoader);
	}

	private static final MagicClassLoader	MAGIC_CLASS_LOADER	= new MagicClassLoader(MagicClassLoader.class.getClassLoader());

	public static MagicClassLoader getClassLoader() {
		return MAGIC_CLASS_LOADER;
	}

	public static Class<?> loadByteCodes(String name, byte[] codes) {
		return MAGIC_CLASS_LOADER.defineClass(name, codes, 0, codes.length);
	}

	public static Class<?> loadClazz(String className) {
		try {
			return MAGIC_CLASS_LOADER.loadClass(className);
		} catch (Throwable throwable) {
			throw Lang.wrapThrow(throwable, "Cannot load the specified class '%s'.", className);
		}
	}

	public static InputStream loadResource(String resourceName) {
		return MAGIC_CLASS_LOADER.getResourceAsStream(resourceName);
	}

	public static URL getResourceURL(String resourceName) {
		return MAGIC_CLASS_LOADER.getResource(resourceName);
	}

	public static String loadResourceText(String resourceName) {
		try {
			InputStreamReader reader = new InputStreamReader(MAGIC_CLASS_LOADER.getResourceAsStream(resourceName), "utf-8");
			StringBuilder builder = new StringBuilder();
			char[] cbuf = new char[1024];
			int size;
			while ((size = reader.read(cbuf)) != -1) {
				builder.append(cbuf, 0, size);
			}
			return builder.toString();
		} catch (IOException e) {
			throw Lang.wrapThrow(e, "Load resource text error");
		}
	}

}
